<template>
  <j-modal :width="1350" :visible.sync="modalVisible" :maskClosable="false" switchFullscreen>
    <template slot="title">
      <div>
        采购单详情(单据号：{{ formData.orderNo }})
        <a-tag :color="colorStatus[formData.status]"> {{ formData.status_dictText }} </a-tag>
      </div>
    </template>
    <a-spin :spinning="submitLoading">
      <a-divider orientation="left"> 基本信息 </a-divider>
      <a-descriptions :column="4">
        <a-descriptions-item label="采购人"> {{ formData.purchaser }} </a-descriptions-item>
        <a-descriptions-item label="成本中心"> {{ formData.costCenterId_dictText }} </a-descriptions-item>
        <a-descriptions-item label="采购方式"> {{ formData.purchaseWay_dictText }} </a-descriptions-item>
        <a-descriptions-item label="收货仓库"> {{ formData.warehouse_dictText }} </a-descriptions-item>
        <a-descriptions-item label="运输方式"> {{ formData.transportWay_dictText }} </a-descriptions-item>
        <a-descriptions-item label="预计到货时间"> {{ formData.expectArrivalTime }} </a-descriptions-item>
        <a-descriptions-item label="结算类型"> {{ formData.settlementType_dictText }} </a-descriptions-item>
        <a-descriptions-item label="结算方式"> {{ formData.settlementWay_dictText }} </a-descriptions-item>
        <a-descriptions-item label="支付方式"> {{ formData.settlementWay_dictText }} </a-descriptions-item>
        <a-descriptions-item label="支付凭证">
          <j-upload-oss v-model="formData.paymentVoucher" fileType="file" :disabled="true" />
        </a-descriptions-item>
        <a-descriptions-item label="买家备注" :span="2"> {{ formData.buyerRemark }} </a-descriptions-item>
        <a-descriptions-item label="给仓库留言" :span="4"> {{ formData.warehouseRemark }} </a-descriptions-item>
        <a-descriptions-item label="备注" :span="4"> {{ formData.remark }} </a-descriptions-item>
      </a-descriptions>
      <a-divider orientation="left"> 产品信息 </a-divider>
      <div class="search-box">
        <a-input-search placeholder="输入SKU、产品名称关键词" size="small" v-model="searchKey" class="input" />
        <div class="total-box">
          <strong>总计：</strong>
          采购总金额:<strong>{{
            formData.purchaseWay == '1' ? '待下单返回' : Number(totalAmount) + Number(formData.totalShippingFee) + '元'
          }}</strong>
          货值:<strong>{{ totalAmount }} <span v-if="formData.purchaseWay == '2'">元</span></strong> 运费:<strong>{{
            formData.purchaseWay == '1' ? '待下单返回' : formData.totalShippingFee + '元'
          }}</strong>
        </div>
      </div>
      <a-table
        bordered
        :pagination="false"
        :scroll="{ x: true, y: 400 }"
        :columns="formColumns"
        :data-source="filterList"
        rowKey="skuCode"
      >
        <template #imgSlot="text, record">
          <a-popover trigger="hover" placement="right">
            <template #content>
              <div class="popover-preview-box">
                <img :src="record.imgUrl" />
              </div>
            </template>
            <viewer :images="[record.imgUrl]" class="img-box">
              <img v-show="record.imgUrl" class="sku-img" :src="record.imgUrl" />
            </viewer>
          </a-popover>
        </template>
        <template #detailSlot="text, record">
          <div>类目:{{ record.categoryName }}</div>
          <div>名称:{{ record.nameCn }}</div>
          <div>颜色/尺寸:{{ record.color }};{{ record.size }}</div>
          <div>单品规格(cm):{{ record.singleSpec }}</div>
          <div>毛重(KG):{{ record.gw }}</div>
          <div>
            质检方式:<span v-if="record.qualityType == 1">免检</span><span v-if="record.qualityType == 3">全检</span
            ><span v-if="record.qualityType == 2">抽检</span>
          </div>
        </template>
        <template #supplierSlot="text, record">
          <template>
            <div>供应商:{{ record.supplierName }}</div>
            <div class="link-item">
              <div>采购链接:</div>
              <a-tooltip :overlayStyle="{ 'min-Width': '700px' }">
                <template slot="title"> {{ record.url || '-' }} </template>
                <div class="link">
                  {{ record.url || '-' }}
                </div>
              </a-tooltip>
            </div>
            <div>
              属性:
              <div v-if="record.supplierType == 1">
                <div v-for="item1 in record.attribute" :key="item1.attributeID">
                  {{ item1.attributeName }}:
                  <span v-for="(val2, index2) in item1.checkVal" :key="index2">{{ val2 }}；</span>
                </div>
              </div>
              <div v-else>{{ record.attribute || '-' }}</div>
            </div>
            <div>最低起订量:{{ record.lowCount }}</div>
          </template>
        </template>
        <template #specSlot="text, record">
          <div>
            供应商规格:
            <span v-if="record.supplierId" :class="{ 'c-red': record.specsSup > 1 }">{{ record.specsSup }}</span
            ><span v-else>-</span>/组
          </div>
          <div>
            入库规格:<span v-if="record.supplierId" :class="{ 'c-red': record.specsMy > 1 }">{{ record.specsMy }}</span
            ><span v-else>-</span>/组
          </div>
          <a-tooltip placement="top">
            <template slot="title">
              供应商规格{{ record.specsSup }}：代表向供应商下单1个含{{ record.specsSup }}件；入库规格{{
                record.specsMy
              }}：代表仓库按照{{ record.specsMy }}个 1 组入库。
            </template>
            <a-icon type="info-circle" />
          </a-tooltip>
        </template>
        <template #warehouseSlot="text, record">
          <div>库名：{{ record.warehouse }}</div>
          <div>待上架：{{ record.pendingListingQuantity }}</div>
          <div>已上架：{{ record.alreadyListedQuantity }}</div>
        </template>
      </a-table>
      <a-divider orientation="left"> 单据相关 </a-divider>
      <a-tabs default-active-key="1" size="small" tab-position="top">
        <a-tab-pane tab="收货批次" key="1">
          <a-table
            class="order-tables"
            :pagination="false"
            bordered
            :scroll="{ x: true, y: 650 }"
            :columns="batchColumns"
            :data-source="batchList"
            rowKey="id"
          >
          </a-table>
        </a-tab-pane>
        <a-tab-pane tab="质检点数单" key="2">
          <a-table
            class="order-tables"
            :pagination="false"
            bordered
            :scroll="{ y: 650 }"
            :columns="qualityColumns"
            :data-source="qualityList"
            rowKey="id"
          >
            <template #qcNoSlot="text, record, index">
              {{ record.qcNo }}
              <a-button
                v-if="index != qualityList.length - 1"
                type="link"
                icon="copy"
                @click="copyTo(record.qcNo)"
              ></a-button>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane tab="上架单" key="3">
          <a-table
            class="order-tables"
            :pagination="false"
            bordered
            :scroll="{ x: true, y: 650 }"
            :columns="upColumns"
            :data-source="upList"
            rowKey="id"
          >
            <template #listingOrderNoSlot="text, record, index">
              {{ record.listingOrderNo }}
              <a-button
                v-if="index != upList.length - 1"
                type="link"
                icon="copy"
                @click="copyTo(record.listingOrderNo)"
              ></a-button>
            </template>
          </a-table>
        </a-tab-pane>
        <!-- <a-tab-pane tab="工单" key="4">
          <a-table
            class="order-tables"
            :pagination="false"
            bordered
            :scroll="{ x: true, y: 650 }"
            :columns="workColumns"
            :data-source="workList"
            rowKey="id"
          >
          </a-table>
        </a-tab-pane> -->
        <a-tab-pane tab="操作记录" key="5">
          <a-table
            class="order-tables"
            :pagination="false"
            bordered
            :scroll="{ x: true }"
            :columns="logColumns"
            :data-source="logList"
            rowKey="id"
          >
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
    <template #footer>
      <a-button @click="modalVisible = false"> 关闭 </a-button>
    </template>
  </j-modal>
</template>

<script>
import copyToClipboard from 'copy-to-clipboard'
import { formatAmount, parseNumber } from '@/utils/number'
import { getAction, postFormAction } from '@/api/manage'

export default {
  data() {
    return {
      colorStatus: {
        1: 'orange',
        2: 'cyan',
        3: 'blue',
        4: 'purple',
        5: 'green',
        6: 'pink',
      },
      modalVisible: false,
      submitLoading: false,
      searchKey: undefined,
      formData: {
        productDetailList: [],
      },
      batchList: [],
      qualityList: [],
      upList: [],
      workList: [],
      logList: [],
      url: {
        queryById: `/hzkj-purchase/purchase/order/info/detail`,
        queryReceivingBatch: `/hzkj-wms/wms/receivingBatch/getReceivingBatchByPoNo`,
        queryQuality: `/hzkj-wms/wms/qualityManage/qualityTestingOrder/list`,
        queryUp: `/hzkj-wms/wms/listing/list`,
        queryLog: `/sys/common/operateLog/list`,
      },
      batchColumns: [
        {
          title: '序号',
          width: 60,
          align: 'center',
          dataIndex: 'index',
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {},
            }
            if (index != 0 && this.batchList[index - 1].index == row.index) {
              obj.attrs.rowSpan = 0
            } else {
              obj.attrs.rowSpan = this.batchList.filter((i) => i.index == row.index).length
            }
            return obj
          },
        },
        {
          title: '收货批次号',
          align: 'center',
          width: 220,
          dataIndex: 'batchNumber',
          customRender: (value, row, index) => {
            const obj = {
              children: (
                <div>
                  {value}
                  {row.id != '0' ? (
                    <a-button type="link" icon="copy" vOn:click={() => this.copyTo(value)}></a-button>
                  ) : null}
                </div>
              ),
              attrs: {},
            }
            if (index != 0 && this.batchList[index - 1].batchNumber == row.batchNumber) {
              obj.attrs.rowSpan = 0
            } else {
              obj.attrs.rowSpan = this.batchList.filter((i) => i.batchNumber == row.batchNumber).length
            }
            return obj
          },
        },
        {
          title: '仓库SKU',
          align: 'center',
          width: 130,
          dataIndex: 'warehouseSku',
        },
        {
          title: '产品名称',
          align: 'center',
          width: 230,
          dataIndex: 'productName',
        },
        {
          title: '颜色/尺寸',
          width: 130,
          align: 'center',
          dataIndex: 'colorSize',
        },
        {
          title: '计划数量',
          align: 'center',
          width: 90,
          dataIndex: 'plannedQty',
        },
        {
          title: '已收数',
          align: 'center',
          width: 80,
          dataIndex: 'receivedQty',
        },
        {
          title: '上架数',
          align: 'center',
          width: 80,
          dataIndex: 'shelvedQty',
        },
        {
          title: '未收数',
          align: 'center',
          width: 80,
          dataIndex: 'unreceivedQty',
        },
        {
          title: '残次数',
          align: 'center',
          width: 80,
          dataIndex: 'defectiveQty',
        },
        {
          title: '通过数',
          align: 'center',
          width: 80,
          dataIndex: 'passedQty',
        },
        {
          title: '实点数',
          align: 'center',
          width: 80,
          dataIndex: 'actualQty',
        },
        {
          title: '是否质检',
          align: 'center',
          width: 90,
          dataIndex: 'qcRequirement',
        },
        {
          title: '收货人',
          align: 'center',
          width: 120,
          dataIndex: 'createBy',
        },
        {
          title: '结束时间',
          align: 'center',
          width: 150,
          dataIndex: 'createTime',
        },
      ],
      qualityColumns: [
        {
          title: '序号',
          width: 60,
          align: 'center',
          dataIndex: 'index',
        },
        {
          title: '单据编号',
          align: 'center',
          scopedSlots: { customRender: 'qcNoSlot' },
        },
        {
          title: '类型',
          align: 'center',
          width: 90,
          dataIndex: 'qcType_dictText',
        },
        {
          title: '实点数量',
          align: 'center',
          width: 90,
          dataIndex: 'totalRealCount',
        },
        {
          title: '残次数量',
          align: 'center',
          width: 90,
          dataIndex: 'totalDefectCount',
        },
        {
          title: '通过数量',
          align: 'center',
          width: 90,
          dataIndex: 'totalPassCount',
        },
        {
          title: '已收数量',
          align: 'center',
          width: 90,
          dataIndex: 'totalReceivedCount',
        },
        {
          title: '送检人',
          align: 'center',
          width: 130,
          dataIndex: 'sender',
        },
        {
          title: '创建时间',
          align: 'center',
          width: 170,
          dataIndex: 'createTime',
        },
        {
          title: '结束时间',
          align: 'center',
          width: 170,
          dataIndex: 'completeTime',
        },
      ],
      upColumns: [
        {
          title: '序号',
          width: 60,
          align: 'center',
          dataIndex: 'index',
        },
        {
          title: '单据编号',
          align: 'center',
          scopedSlots: { customRender: 'listingOrderNoSlot' },
        },
        {
          title: 'SKU',
          align: 'center',
          dataIndex: 'sku',
        },
        {
          title: '产品名称',
          align: 'center',
          dataIndex: 'productName',
        },
        {
          title: '颜色/尺寸',
          align: 'center',
          dataIndex: 'colorSize',
        },
        {
          title: '等待上架数量',
          align: 'center',
          dataIndex: 'waitListingNum',
        },
        {
          title: '实际上架数量',
          align: 'center',
          dataIndex: 'actualListingNum',
        },
        {
          title: '存放库位',
          align: 'center',
          dataIndex: 'location',
        },
        {
          title: '上架时间',
          align: 'center',
          dataIndex: 'listingTime',
        },
      ],
      workColumns: [
        {
          title: '工单编号',
          align: 'center',
        },
        {
          title: '标题',
          align: 'center',
        },
        {
          title: '分类',
          align: 'center',
        },
        {
          title: '工单状态',
          align: 'center',
        },
        {
          title: '创建人',
          align: 'center',
        },
        {
          title: '处理人',
          align: 'center',
        },
        {
          title: '协作人',
          align: 'center',
        },
        {
          title: '提交时间',
          align: 'center',
        },
      ],
      logColumns: [
        {
          title: '序号',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender(t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '操作人',
          align: 'center',
          dataIndex: 'user',
        },
        {
          title: '操作时间',
          align: 'center',
          dataIndex: 'operateTime',
        },
        {
          title: '操作类型',
          align: 'center',
          dataIndex: 'operateType_dictText',
        },
        {
          title: '操作内容',
          align: 'center',
          dataIndex: 'content',
          width: 500,
          scopedSlots: { customRender: 'contentSlot' },
        },
      ],
    }
  },
  computed: {
    filterList() {
      if (!this.searchKey) {
        return this.formData.productDetailList
      }
      return this.formData.productDetailList.filter(
        (item) => item.nameCn.indexOf(this.searchKey) > -1 || item.skuCode.indexOf(this.searchKey) > -1
      )
    },
    formColumns() {
      let arr = [
        {
          title: '序号',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender(t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: 'SKU',
          width: 130,
          align: 'center',
          dataIndex: 'skuCode',
        },
        {
          title: '主图',
          dataIndex: 'imgSlot',
          width: 110,
          align: 'center',
          scopedSlots: { customRender: 'imgSlot' },
        },
        {
          title: '产品信息',
          width: 200,
          scopedSlots: { customRender: 'detailSlot' },
        },
        {
          title: '供应商',
          width: 300,
          scopedSlots: { customRender: 'supplierSlot' },
        },
        {
          title: '采购入库关系',
          width: 150,
          scopedSlots: { customRender: 'specSlot' },
        },
        {
          title: '采购数量',
          width: 130,
          align: 'center',
          dataIndex: 'purchaseQuantity',
        },
        this.formData.purchaseWay == '1'
          ? {
              title: '下单数量(供应商)',
              width: 150,
              align: 'center',
              dataIndex: 'orderQuantity',
              customRender(t, record) {
                if (!record.purchaseQuantity || !record.specsMy || !record.specsSup) {
                  return 0
                }
                let purchaseQuantity = parseNumber(record.purchaseQuantity)
                let specsMy = parseNumber(record.specsMy)
                let specsSup = parseNumber(record.specsSup)
                return formatAmount((purchaseQuantity * specsMy) / specsSup, 4)
              },
            }
          : null,
        {
          title: '采购单价(元)',
          width: 120,
          align: 'center',
          dataIndex: 'unitPrice',
        },
        {
          title: '采购总价(元)',
          width: 120,
          align: 'center',
          customRender: (t, record) => {
            if (this.formData.purchaseWay == '1') {
              // 1688采购的金额信息需要等待1688返回
              if (['1', '6'].includes(this.formData.status)) {
                // 如果是新增或者订单状态是草稿和取消的订单，则待下单返回
                return '待1688下单返回'
              } else {
                return record.totalPrice
              }
            } else {
              return formatAmount(parseNumber(record.unitPrice) * parseNumber(record.purchaseQuantity), 3)
            }
          },
        },
        {
          title: '仓库',
          width: 180,
          align: 'center',
          scopedSlots: { customRender: 'warehouseSlot' },
        },
        {
          title: '给仓库留言',
          width: 250,
          align: 'center',
          dataIndex: 'warehouseRemark',
        },
      ]

      return arr.filter((i) => i)
    },
    totalAmount() {
      if (this.formData.purchaseWay == '1') {
        // 1688采购的金额信息需要等待1688返回
        if (['1', '6'].includes(this.formData.status)) {
          // 订单状态是草稿和取消的订单，则待下单返回
          return '待下单返回'
        } else {
          return this.formData.totalAmount
        }
      } else {
        // 其他类型的采购为计算出的金额之和
        if (!this.formData.productDetailList.length) {
          return 0
        }
        let total = this.formData.productDetailList.reduce((total, next) => {
          return parseNumber(next.unitPrice) * parseNumber(next.purchaseQuantity) + total
        }, 0)
        return formatAmount(total + parseNumber(this.formData.totalShippingFee), 3)
      }
    },
  },
  methods: {
    api_open(id, otherData = {}) {
      this.modalVisible = true
      this.submitLoading = true
      this.searchKey = undefined
      Promise.all([
        this.queryDetail(id, otherData),
        this.queryQuality(otherData.orderNo),
        this.queryUp(otherData.orderNo),
        this.queryLog(id),
      ]).then(() => {
        this.submitLoading = false
      })
    },
    // 复制到剪贴板
    copyTo(value) {
      try {
        copyToClipboard(value)
        this.$message.success(`已复制：${value}`)
      } catch (e) {
        this.$message.error('复制失败')
      }
    },

    queryDetail(id, otherData) {
      return getAction(this.url.queryById, { id }).then((res) => {
        if (res.success) {
          this.trackingNumberArr = res.result.trackingNumber ? res.result.trackingNumber.split(',') : []
          this.formData = {
            ...otherData,
            ...res.result,
            trackingNumber: '',
            productDetailList: res.result.productDetailList.map((i) => ({
              ...i,
              attribute: i.supplierType == '1' ? JSON.parse(i.attribute) : i.attribute,
            })),
          }
          this.queryReceivingBatch(otherData.orderNo)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    queryReceivingBatch(poNo) {
      return postFormAction(this.url.queryReceivingBatch, { poNo }).then((res) => {
        if (res.success) {
          // 数据拼入产品信息
          let dataArr = res.result.map((i) => {
            let productDetail = this.formData.productDetailList.find((i2) => i2.skuCode == i.warehouseSku)
            console.log('productDetail', productDetail)
            return {
              ...i,
              productName: productDetail.nameCn,
              colorSize: productDetail.color + ';' + productDetail.size,
            }
          })
          // 相同批次编号要进行表格合并
          let batchNumbers = dataArr.map((i) => i.batchNumber)
          let endArr = []
          batchNumbers.forEach((i, index) => {
            let arr = dataArr.filter((i2) => i2.batchNumber == i).map((i2) => ({ ...i2, index: index + 1 }))
            endArr = [...endArr, ...arr]
          })
          endArr.push({
            index: '合计',
            id: '0',
            plannedQty: endArr.reduce((total, next) => total + parseNumber(next.plannedQty), 0),
            receivedQty: endArr.reduce((total, next) => total + parseNumber(next.receivedQty), 0),
            shelvedQty: endArr.reduce((total, next) => total + parseNumber(next.shelvedQty), 0),
            unreceivedQty: endArr.reduce((total, next) => total + parseNumber(next.unreceivedQty), 0),
            defectiveQty: endArr.reduce((total, next) => total + parseNumber(next.defectiveQty), 0),
            passedQty: endArr.reduce((total, next) => total + parseNumber(next.passedQty), 0),
            actualQty: endArr.reduce((total, next) => total + parseNumber(next.actualQty), 0),
          })
          this.batchList = endArr
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    queryQuality(poNo) {
      return getAction(this.url.queryQuality, { poNo, pageNo: 1, pageSize: 9999 }).then((res) => {
        if (res.success) {
          let list = res.result.records.map((i, index) => ({
            ...i,
            index: index + 1,
          }))
          list.push({
            index: '合计',
            id: '0',
            totalRealCount: list.reduce((total, next) => total + parseNumber(next.totalRealCount), 0),
            totalDefectCount: list.reduce((total, next) => total + parseNumber(next.totalDefectCount), 0),
            totalPassCount: list.reduce((total, next) => total + parseNumber(next.totalPassCount), 0),
            totalReceivedCount: list.reduce((total, next) => total + parseNumber(next.totalReceivedCount), 0),
          })
          this.qualityList = list
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    queryUp(orderNo) {
      return getAction(this.url.queryUp, { orderNo, pageNo: 1, pageSize: 9999 }).then((res) => {
        if (res.success) {
          let list = res.result.records.map((i, index) => ({
            ...i,
            index: index + 1,
          }))
          list.push({
            index: '合计',
            id: '0',
            waitListingNum: list.reduce((total, next) => total + parseNumber(next.waitListingNum), 0),
            actualListingNum: list.reduce((total, next) => total + parseNumber(next.actualListingNum), 0),
          })
          this.upList = list
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    queryLog(id) {
      return getAction(this.url.queryLog, { id: id, pageNo: 1, pageSize: 9999 }).then((res) => {
        if (res.success) {
          this.logList = res.result.records
        } else {
          this.$message.warning(res.message)
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
.popover-preview-box {
  width: 300px;
  height: 300px;
  position: relative;
  background-color: #fafafa;
  img {
    max-height: 100%;
    max-width: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
.img-box {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  display: inline-block;
  cursor: pointer;
  position: relative;
  background-color: #fafafa;
  img {
    width: 100%;
    height: 100%;
  }
}
.c-red {
  color: #ff4d4f;
}
.link-item {
  display: flex;
  .link {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
  }
}

.search-box {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;

  .input {
    width: 300px;
  }

  .total-box {
    font-size: 14px;
  }
}

.order-tables {
  margin-top: 20px;
}
</style>
